import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import calendar

# Load data
file_path = r'C:\Users\SBD Lab\Desktop\be_hourly_2024.xlsx'
df = pd.read_excel(file_path)
df.columns = df.columns.str.strip()

# Parse datetime
df['Datetime'] = pd.to_datetime(df['Datetime (UTC)'], dayfirst=True, errors='coerce')

# Extract day of year, hour, month
df['DayOfYear'] = df['Datetime'].dt.dayofyear
df['Hour'] = df['Datetime'].dt.hour
df['Month'] = df['Datetime'].dt.month

# Pivot for heatmap
heatmap_data = df.pivot(index='Hour', columns='DayOfYear', values='Carbon intensity gCOâ‚‚eq/kWh (direct)')

plt.figure(figsize=(20, 8))
ax = sns.heatmap(
    heatmap_data,
    cmap='RdYlGn_r',
    cbar_kws={
        'label': 'Carbon intensity [gCO\u2082/kWh]',
        'orientation': 'horizontal',
        'pad': 0.15
    }
)

# Title and labels
ax.set_title('Hourly Carbon Intensity (Belgium 2024)', fontsize=18, weight='bold')
ax.set_ylabel('Hours', fontsize=16)
ax.set_xlabel('Day 2024', fontsize=16, labelpad=25)

# Month start days for ticks
month_starts = df.groupby('Month')['DayOfYear'].min().sort_index()
month_ends = df.groupby('Month')['DayOfYear'].max().sort_index()

# Calculate midpoints of each month for ticks
month_positions = ((month_starts + month_ends) / 2).values - 1  # zero-based index for heatmap columns

# Set ticks and labels
ax.set_xticks(month_positions)
ax.set_xticklabels([calendar.month_abbr[m] for m in range(1, 13)], fontsize=14, rotation=0)

# Y ticks every 2 hours
ax.set_yticks(range(0, 24, 2))
ax.set_yticklabels(range(0, 24, 2), fontsize=14)

# Adjust layout to reduce space between xlabel and colorbar
plt.subplots_adjust(bottom=0.22)
plt.tight_layout()
plt.show()
